//
//  PlayersViewController.m
//  NBAPro
//
//  Created by 李广松 on 16/6/27.
//  Copyright © 2016年 WYH. All rights reserved.
//

#import "PlayersViewController.h"

@implementation PlayersViewController {
    
    UITableView *playersTableView;
    
    NSArray *allPlayersArr;
    NSMutableArray *playersArr;
    NSMutableDictionary *playerTeamDic;
    
    NSMutableArray *playersId;
    
    UITextField *searchTextField;
    
}

- (void)viewDidAppear:(BOOL)animated {
    searchTextField.text = @"";
    [searchTextField resignFirstResponder];
    [playersArr removeAllObjects];
    [playersTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialData];
    
    UIView *titleView = [self createTitleWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) AndBackgroundColor:[UIColor colorWithRed:221/255.0 green:82/255.0 blue:50/255.0 alpha:1]];
    [self.view addSubview:titleView];
    
    
    playersTableView = [self createTableViewWithFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
    [self.view addSubview:playersTableView];
    
    [self getPlayersInfo];

    
    UIView *searchView = [self createSearchViewWithFrame:CGRectMake(40, 110 / 2 - 40 / 2, self.view.frame.size.width - 80, 40)];
    [self.view addSubview:searchView];
    
    
    [self createKeyboardHidden];
}



#pragma mark - 获取all players
- (void)getPlayersInfo {
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@commonallplayers?IsOnlyCurrentSeason=1&LeagueID=00&Season=2015-16", API_BASE_URL_NBA];
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            [self performSelectorOnMainThread:@selector(getPlayersArr:) withObject:dataDic waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
};


- (void)getPlayersArr:(NSDictionary *)dataDic {
    allPlayersArr = dataDic[@"resultSets"][0][@"rowSet"];
    
}

- (void)getPlayers {
    
    [playersId removeAllObjects];
    [playersArr removeAllObjects];
    
    NSString *lowerSearch = [searchTextField.text lowercaseString];
    
    for (int i = 0; i < allPlayersArr.count; i++) {
        NSString *lowerAll = [allPlayersArr[i][1] lowercaseString];
        
        if ([lowerAll containsString:lowerSearch]) {
            [playersArr addObject:allPlayersArr[i][2]];
            [playerTeamDic setObject:allPlayersArr[i][9] forKey:allPlayersArr[i][2]];
            id playeridFlo = allPlayersArr[i][0];
            NSString *playerIdStr = [[NSString alloc] initWithFormat:@"%@", playeridFlo];
            [playersId addObject:playerIdStr];
        }
    }
    
}


- (void)textFieldDidChange {
    [self getPlayers];
    [playersTableView reloadData];
    
}


#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self getPlayers];
    [playersTableView reloadData];
}


#pragma mark - UITableViewDataSouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return playersArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    else{
        // 删除cell中的子对象,解决覆盖问题。
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }

    
    UILabel *downCutLab = [self createCellDownCutLab:CGRectMake(0, 60 - 1, self.view.frame.size.width, 1)];
    [cell addSubview:downCutLab];
    
    cell.textLabel.text = playersArr[indexPath.row];
    cell.textLabel.textColor = [UIColor colorWithRed:89/255.0 green:105/255.0 blue:133/255.0 alpha:1];

    cell.detailTextLabel.text = playerTeamDic[playersArr[indexPath.row]];
    
    cell.detailTextLabel.textColor = [UIColor colorWithRed:168/255.0 green:175/255.0 blue:191/255.0 alpha:1];
    
    UIImageView *imgView = [self createCellImgViewWithFrame:CGRectMake(self.view.frame.size.width - 12 - 20, 60 / 2 - 15 / 2, 10, 17)];
    [cell addSubview:imgView];
    
    return cell;
}

- (UIImageView *)createCellImgViewWithFrame:(CGRect)frame {
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:frame];
    imgView.image = [UIImage imageNamed:@"edit_arrow_right"];
    
    return imgView;
}


- (UILabel *)createCellDownCutLab:(CGRect)frame {
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.backgroundColor = [UIColor colorWithRed:162/255.0 green:162/255.0 blue:162/255.0 alpha:1];
    
    return label;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PlayerInfoViewController *playerInfoViewController = [[PlayerInfoViewController alloc] initWithPlayerId:playersId[indexPath.row]];
    [self.navigationController pushViewController:playerInfoViewController animated:YES];
    
}

#pragma mark - 界面
- (UIView *)createTitleWithFrame:(CGRect)frame AndBackgroundColor:(UIColor *)color{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = color;
    
    return view;
}


- (void)createKeyboardHidden {
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
}


- (UITableView *)createTableViewWithFrame: (CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    return tableView;
}

- (UIView *)createSearchViewWithFrame:(CGRect)frame {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    
    [self createSearchTextFieldWithFrame:CGRectMake(5, 0, frame.size.width - 5 - 30, frame.size.height)];
    [view addSubview:searchTextField];
    
    UIImageView *searchImgView = [[UIImageView alloc] initWithFrame:CGRectMake(frame.size.width - 30, frame.size.height / 2 - 12.5, 25, 25)];
    searchImgView.image = [UIImage imageNamed:@"search"];
    [view addSubview:searchImgView];
    
    return view;
}

- (void)createSearchTextFieldWithFrame:(CGRect)frame {
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(5, 0, frame.size.width - 5 - 30, frame.size.height)];
    searchTextField.textColor = [UIColor whiteColor];
    searchTextField.font = [UIFont systemFontOfSize:17];
    [searchTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    searchTextField.delegate = self;
}

- (void)initialData {
    playersArr = [[NSMutableArray alloc] init];
    playerTeamDic = [[NSMutableDictionary alloc] init];
    playersId = [[NSMutableArray alloc] init];
    
}

#pragma mark - 其他

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [searchTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}


@end
